import { canvasToBlob } from '@/utils/common'
import imageLoadManager from './imageLoadManager'

export async function imageClip(
  frameInfo: FrameInfo[],
  rect: {
    left: number
    top: number
    right: number
    bottom: number
  },
  onProgress?: (current: number, length: number) => void
): Promise<FrameInfo[]> {
  const list: FrameInfo[] = []

  const canvas = document.createElement('canvas')
  canvas.width = rect.right - rect.left
  canvas.height = rect.bottom - rect.top
  const ctx = canvas.getContext('2d')

  if (!ctx) {
    throw new Error('Failed to get 2d context')
  }

  const imageList = await imageLoadManager.loadImageList(frameInfo)
  for (let i = 0; i < imageList.length; i++) {
    const image = imageList[i]
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(
      image,
      rect.left,
      rect.top,
      canvas.width,
      canvas.height,
      0,
      0,
      canvas.width,
      canvas.height
    )
    const blob = await canvasToBlob(canvas)
    const file = new File([blob], frameInfo[i].name, { type: blob.type })
    list.push({
      name: file.name,
      file,
      url: URL.createObjectURL(file),
    })
    onProgress?.(i + 1, imageList.length)
  }
  return list
}
